import axios from 'axios'
import { Message } from 'element-ui'
import { getToken, removeToken, setExpire } from '@/utils'

let hasMessage = false
const instance = axios.create({
  timeout: 60000,
  baseURL: 'http://121.43.57.185:8088'
})

instance.interceptors.request.use(
  config => {
    config.headers.token = getToken()
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  response => {
    if (response.config.responseType === 'blob') {
      return response
    }
    // 2xx
    const {
      code,
      message
    } = response.data || {}
    if (code !== 200) {
      if ((code === 401 || code === 406) && !hasMessage) {
        removeToken()
        setTimeout(() => {
          location.reload()
        }, 20)
        // hasMessage = true
        // return MessageBox.confirm(message || '登录超时，请重新登录', '温馨提示')
        //   .then(() => {
        //     hasMessage = false
        //     removeToken()
        //     setTimeout(() => {
        //       location.reload()
        //     }, 20)
        //   })
        //   .catch(() => {
        //     hasMessage = false
        //   })
      }
      if (!hasMessage) {
        hasMessage = true
        Message.error({
          message,
          onClose () {
            hasMessage = false
          }
        })
      }
      return Promise.reject(new Error(message))
    }
    setExpire(Date.now())
    return response.data
  },
  error => {
    // >2xx
    if (!hasMessage) {
      hasMessage = true
      Message.error({
        message: (error && error.message) ? error.message : '系统异常',
        onClose () {
          hasMessage = false
        }
      })
    }
    return Promise.reject(error)
  }
)

export default instance
